package org.an.demo.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * Created by zhangqiang on 2016/5/12.
 */
public class AdaptiveTextView extends TextView {

  private static final boolean DEBUG = true;

  private static final String TAG = "AdaptiveTextView";

  private static final String NAMESPACE = "http://schemas.android.com/apk/res/android";

  private static final String ATTR_MAX_EMS = "maxEms";

  private static final int DEFAULT_MAX_EMS = 20;

  /** 设定显示字个数 */
  private int mMaxEms;

  public AdaptiveTextView(Context context) {
    super(context);
  }

  public AdaptiveTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mMaxEms = attrs.getAttributeIntValue(NAMESPACE, ATTR_MAX_EMS, DEFAULT_MAX_EMS);
  }

  @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int width = getMeasuredWidth();
    int height = getMeasuredHeight();

    Paint paint = getPaint();
    //String holder = "...";
    //float holderWidth = paint.measureText(holder);
    int unitSize = (int) getTextSize();//每个字宽度
    int textTotalWidth = (int) paint.measureText(getText().toString());//文字总宽度
    int textNums = textTotalWidth / unitSize;//字个数
    if (textNums >= mMaxEms) {//字个数不超过mMaxEms
      textTotalWidth = mMaxEms * unitSize;
    }
    if (textTotalWidth >= width) {//字总宽度不要超过测量宽度
      textTotalWidth = width;
    }

    setMeasuredDimension(textTotalWidth, resolveSize(height, heightMeasureSpec));
  }

  @Override protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
  }
}
